import { Collection, DatasetListItem } from '@/common';
import DatasetHeader from './DatasetHeader';
import RoleTable from './RoleTable';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { useEffect, useRef, useState } from 'react';
import { useSize } from 'ahooks';
import NewApiModal from './NewRoleModal';
import { useContextSelector } from 'use-context-selector';
import { RoleManageContext } from '../context';
import { Role } from '@/types/role';
import RoleParentTable from './RoleParentTable';
import Statements from './Statements';

interface Props {
  selectedItem: Role | undefined;
  datas: Role[];
  isAdmin: boolean;
  isPermit: boolean;
  onItemClicked?: (item: Role | undefined) => void;
  version?: string;
}

const RoleListTableMain = ({
  selectedItem,
  datas,
  isAdmin,
  isPermit,
  onItemClicked,
  version,
}: Props) => {
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);

  const handleDeleteConfirm = async () => {
    setDeleteModalVisible(false);
    onItemClicked && onItemClicked(undefined);
  };

  return (
    <>
      <div className="mt-2 bg-[#F5F7FB]" style={{ borderRadius: '15px 15px 0px 0' }}>
        <DatasetHeader
          selectedItem={selectedItem}
          isAdmin={isAdmin}
          isPermit={isPermit}
          parentSize={size ?? { width: 0, height: 0 }}
          onDeleteClicked={() => {
            setDeleteModalVisible(true);
          }}
          version={version}
        />
      </div>
      <div ref={ref} className="h-full flex-1 overflow-y-auto overflow-x-hidden bg-[#F5F7FB]">
        {selectedItem && (
          <Statements
            conditions={selectedItem.statements}
            parentSize={size ?? { width: 0, height: 0 }}
            isAdmin={isAdmin}
          />
        )}
        {!selectedItem && (
          <RoleParentTable
            datas={datas}
            isAdmin={isAdmin}
            isPermit={isPermit}
            parentSize={size ?? { width: 0, height: 0 }}
            onItemClicked={onItemClicked}
          />
        )}
        <DeleteConfirmModal
          visible={deleteModalVisible}
          text={`确定要删除数据接口集 ${selectedItem?.name} 吗？`}
          onCancel={() => {
            setDeleteModalVisible(false);
          }}
          onConfirm={handleDeleteConfirm}
        />
      </div>
    </>
  );
};

export default RoleListTableMain;
